<template>
  <div class="jcx-form-table" ref="jcxFormTableRef">
    <el-table :data="treeList" ref="tableRef" border :row-style="myFormTableRowStyle" :row-key="props.treeProps?.id"
              :tree-props="{ children: props.treeProps?.children }" :indent="5" default-expand-all>
      <el-table-column width="80" label="展开" align="center"></el-table-column>
      <el-table-column width="80" label="层级" type="index" align="center" fixed="left">
        <template #header>
          <el-tooltip content="添加主项" placement="top" v-if="addMain">
            <el-button type="primary" size="small" plain circle icon="el-icon-plus" @click="rowAdd"></el-button>
          </el-tooltip>
        </template>
        <template #default="scope">
          <div class="jcx-form-table-handle , jcx-form-table-handle-delete">
            <span>{{ scope.row.nodeNumber }}</span>
            <el-button type="danger" size="small" plain circle icon="el-icon-delete"
                       @click="rowDel(scope.row)"></el-button>
          </div>
        </template>
      </el-table-column>
      <slot></slot>
      <el-table-column width="60" label="添加子项" align="center" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" plain circle icon="el-icon-plus"
                     @click="subRowAdd(scope.row,[])"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        {{ placeholder }}
      </template>
    </el-table>
  </div>
</template>

<script setup>
import {ref, onMounted, watch} from "vue";
import treeUtils from "@/utils/tree";
import toolUtils from "@/utils/tool";

const treeList = ref([]);
const dataList = ref([]);
const jcxFormTableRef = ref(null);
const tableRef = ref(null);

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  addTemplate: {
    type: Object,
    default: () => {
    }
  },
  placeholder: {
    type: String,
    default: "暂无数据"
  },
  formTableRowStyle: {
    type: Function,
    default: () => {
    }
  },
  treeProps: {
    type: Object,
    default: {id: 'id', parentId: 'parentId', children: 'children'}
  },
  addMain: {
    type: Boolean,
    default: true
  }
});

const emit = defineEmits(['update:modelValue', 'formTableRowStyle']);

// 递归给树形结构的节点赋予层级序号
const assignNodeNumbers = (nodes, parentNumbers = []) => {
  // 初始序号
  let count = 1;
  for (const node of nodes) {
    // 构建当前节点的序号数组
    const nodeNumbers = [...parentNumbers, count++];
    // 设置当前节点的序号
    node.nodeNumber = nodeNumbers.join('.');
    // 递归处理子节点
    if (node[props.treeProps.children]?.length > 0) {
      assignNodeNumbers(node[props.treeProps.children], nodeNumbers);
    }
  }
};

watch(() => treeList.value, () => {
  assignNodeNumbers(treeList.value);
}, {deep: true});

onMounted(() => {
  dataList.value = props.modelValue;
});

watch(() => props.modelValue, () => {
  dataList.value = props.modelValue;
}, {deep: true});

watch(() => dataList.value, () => {
  treeList.value = treeUtils.buildTree(props.modelValue, props.treeProps?.id, props.treeProps?.parentId, props.treeProps?.children);
}, {deep: true});

const myFormTableRowStyle = (row) => {
  return props.formTableRowStyle ? props.formTableRowStyle(row) : {};
}

const rowAdd = () => {
  const temp = JSON.parse(JSON.stringify(props.addTemplate));
  temp[props.treeProps?.id] = toolUtils.makeId();
  temp[props.treeProps?.parentId] = '0';
  temp[props.treeProps?.children] = [];
  treeList.value.push(temp);
  const flattenList = treeUtils.flattenTree(treeList.value, props.treeProps?.id, props.treeProps?.children);
  emit('update:modelValue', flattenList);
}

const subRowAdd = (row) => {
  if (!row[props.treeProps?.children]) {
    row[props.treeProps?.children] = [];
  }
  const temp = JSON.parse(JSON.stringify(props.addTemplate));
  temp[props.treeProps?.id] = gen1.NextId().toString();
  temp[props.treeProps?.parentId] = row[props.treeProps?.id];
  temp[props.treeProps?.children] = [];
  row[props.treeProps?.children].push(temp);
  const flattenList = treeUtils.flattenTree(treeList.value, props.treeProps?.id, props.treeProps?.children);
  emit('update:modelValue', flattenList);
}

const rowDel = (row) => {
  deleteRowById(props.treeProps?.id, row[props.treeProps?.id]);
  const flattenList = treeUtils.flattenTree(treeList.value, props.treeProps?.id, props.treeProps?.children);
  emit('update:modelValue', flattenList);
}

const deleteRowById = (key, value) => {
  const deleteRecursive = (nodes) => {
    for (let i = 0; i < nodes.length; i++) {
      const node = nodes[i];
      if (node[key] === value) {
        // 删除当前节点
        nodes.splice(i, 1);
        // 减少索引，因为数组长度减小了
        i--;
        // 继续下一轮循环，避免跳过节点
        continue;
      }
      // 递归处理子节点
      if (node[props.treeProps?.children]?.length > 0) {
        deleteRecursive(node[props.treeProps?.children]);
      }
    }
  };
  // 在树形数据中查找并删除节点
  deleteRecursive(treeList.value);
};

defineExpose({
  subRowAdd,
  rowDel
})
</script>

<style scoped>
.jcx-form-table {
  width: 100%;
}

.jcx-form-table .jcx-form-table-handle {
  text-align: center;
}

.jcx-form-table .jcx-form-table-handle span {
  display: inline-block;
}

.jcx-form-table .jcx-form-table-handle button {
  display: none;
}

.jcx-form-table .hover-row .jcx-form-table-handle-delete span {
  display: none;
}

.jcx-form-table .hover-row .jcx-form-table-handle-delete button {
  display: inline-block;
}

.jcx-form-table .move {
  text-align: center;
  font-size: 14px;
  margin-top: 3px;
}
</style>
